package organizer.resources;

import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.HashMap;

public class ResourceFactory {
	private static ResourceFactory instance = null;

	private static HashMap<String, Image> imageList = null;

	public static ResourceFactory get() {
		if(instance == null) {
			instance = new ResourceFactory();
		}
		return instance;
	}

	private ResourceFactory() {
		imageList = new HashMap<String, Image>();

		loadImageArray("number_arr", 2, 5, false);
	}

	public Image loadImage(String ref) {
		URL resource = instance.getClass().getClassLoader()
				.getResource("images\\" + ref);
		Image image = null;
		if (resource != null) {
			System.out.println("Resource: Image: " + ref);
			image = Toolkit.getDefaultToolkit().createImage(resource);
		}
		return image;
	}

	public Image getImage(String ref) {
		System.out.println(imageList);
		if (imageList.containsKey(ref)) {
			return imageList.get(ref);
		} else {
			Image image = loadImage(ref);
			imageList.put(ref, image);
			return image;
		}
	}

	public void loadImageArray(String ref, int rows, int cols,
			boolean loadFullImage) {
		if (loadFullImage) {
			BufferedImage fullImage = (BufferedImage) loadImage(ref);

			String key = ref.substring(0, ref.indexOf("_arr"));
			imageList.put(key, fullImage);

			int subWidth = fullImage.getWidth() / cols;
			int subHeight = fullImage.getHeight() / rows;

			int counter = 0;
			for (int row = 0; row < rows; row++) {
				for (int col = 0; col < cols; col++) {
					Image subImage = fullImage.getSubimage(col * subWidth, row
							* subHeight, subWidth, subHeight);
					imageList.put(key + counter, subImage);
				}
			}
		}
	}
}
